/****************************************************
          File Name:46-1-msgsnd.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Thu 11 Sep 2014 03:31:42 PM CST
*****************************************************/

#include"msg.h"
#include<string.h>

int main(int argc,char *argv[])
{
    if(strcmp(argv[1],"--help")==0)
    {
        printf("%s msgid -t mtype mtext\nor\n%s msgid -t mtype\
                mtext -f(IPC_NOWAIT)\n",argv[0],argv[0]);
        exit(1);
    }

    int flag=0, opt,len,msgid;
    int status;
    struct msgbuf msgp;
    msgid=atoi(argv[1]);

    while((opt=getopt(argc,argv,"t:f"))!=-1)
    {
        if(opt=='f')
            flag|=IPC_NOWAIT;
        if(opt=='t')
        {
            msgp.mtype=atoi(argv[optind-1]);
            len=strlen(argv[optind]);
            memcpy(msgp.mtext,argv[optind],len);
        }
    }
    if(msgp.mtext==NULL)
        err("memcpy");
    //msgp.mtext[len-1]='\0';

    status=msgsnd(msgid,&msgp,len,flag);

    if(status==-1)
        err("msgsnd");

    exit(0);
}
